package com.keyinong.caizhengting.activity;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.ListViewForScrollView;
import com.keyinong.caizhengting.tools.MyShowDialog;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.adapter.CaidanAdapter;
import com.keyinong.caizhengting.entity.CaidanEntity;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;

/**
 * @author：郑谦
 * @时间：2017-4-10 下午4:02:27
 * @类名：QuedingdingdanActivity.java
 * @功能: 确定订单
 */

public class QuedingdingdanActivity extends Activity {
    View iscatview = null;
    /**
     * 确定并提交
     */
    Button btn_queren;
    /**
     * 备注
     */
    EditText et_beizhu;
    /**
     * 送货时间
     */
    TextView tv_time;
    //	TextView tv_riqi;
    RelativeLayout ll_time;
    RelativeLayout ll_date;
    /**
     * 收货时间
     */
    String shouhuo;
    String date;
    String riqi;
    String book;
    /**
     * 获得数据
     */
    ArrayList<CaidanEntity> infolist;
    HttpTools httptools = null;
    int current_select = 0;
    String returnInfo = "";
    ArrayList<String> listtime;
    String systime;
    String orderid;
    String token;
    private CaidanAdapter caidanAdapter;
    /**
     * 菜单列表
     */
    private ListViewForScrollView lv;
    private ScrollView sl;
    /**
     * 合计
     */
    private TextView tv_heji;
    private double heji;
    // 判断listview点击的下标
    private int shuliang;
    private boolean flag = true;
    private int mHour;
    private int mMinute;
    private Calendar calendar = Calendar.getInstance(); //通过Calendar获取系统时间
    /**
     * 返回
     */
    private ImageButton ib_fanhui;

    private int mType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//			getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_quedingdingdan);
//		initRes();		
//		MyShowDialog.closeLoadingDialog();
        Intent intent = getIntent();
        if (null != intent) {
            mType = intent.getIntExtra("type", 0);
        }

        Caidan();
    }

    private void initRes() {
        lv = (ListViewForScrollView) findViewById(R.id.lv_dingdan);
        sl = (ScrollView) findViewById(R.id.sl);
        sl.smoothScrollTo(0, 0);
        tv_heji = (TextView) findViewById(R.id.tv_dingdanheji);

        /**返回*/
        ib_fanhui = (ImageButton) findViewById(R.id.ib_fanhui);
        ib_fanhui.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        /**收货时间*/
        tv_time = (TextView) findViewById(R.id.tv_shijian);
        ll_time = (RelativeLayout) findViewById(R.id.linearlayout6);
        if (mType != 0) {
            ll_time.setVisibility(View.GONE);
        }
        ll_time.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new TimePickerDialog(QuedingdingdanActivity.this,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hour, int minute) {
                                // TODO Auto-generated method stub
                                mHour = hour;
                                mMinute = minute;
                                //更新EditText控件时间 小于10加0
                                double min = mMinute;
                                double xiaoshi = mHour;
                                double x = xiaoshi + min / 60;
//		                   if (!date.substring(8, 10).equals(riqi)) {
                                if ((10 <= x && x <= 12.5) || (15 <= x && x <= 18)) {
                                    tv_time.setText(new StringBuilder()
                                            .append(mHour < 10 ? "0" + mHour : mHour).append(":")
                                            .append(mMinute < 10 ? "0" + mMinute : mMinute));
                                } else {
                                    Toast.makeText(QuedingdingdanActivity.this, "不在订餐时间内", Toast.LENGTH_SHORT).show();
                                    tv_time.setText("18:00");
                                    mHour = 18;
                                    mMinute = 00;
                                }


                            }
                        }, calendar.get(Calendar.HOUR_OF_DAY),
                        calendar.get(Calendar.MINUTE), true).show();
            }
        });

        /**提交*/
        btn_queren = (Button) findViewById(R.id.btn_queren);
        btn_queren.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if (flag) {
                    SharedPreferences sp = getSharedPreferences("spReg", Context.MODE_PRIVATE);
                    String token = sp.getString("data", "");
                    if (tv_time.getText().equals("12:00")) {
                        book = date + " " + "12:00";
                    } else if (tv_time.getText().equals("18:00")) {
                        book = date + " " + "18:00";
                    } else {
                        book = date + " " + mHour + ":" + mMinute + ":00";
                    }
                    if (httptools == null) {
                        httptools = new HttpTools(getApplicationContext());
                    }
//					Log.e("lh", "token=="+token);
//					Log.e("lh", "book=="+book);
                    //httptools.newSaveOrder(token, book, new ConfirmOrderResponse());
                    if (mType == 0) {
                        httptools.saveFoodOrder(token, book, new ConfirmOrderResponse());
                    } else {
                        httptools.saveGoodsOrder(token, new ConfirmOrderResponse());
                    }
                }
                flag = false;
            }
        });
    }

    private void submitGoodsOrder(int orderId) {
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        httptools.submitGoods(token, orderId, new SubmitGoodsHandler());
    }

    /**
     * 菜单
     */
    private void Caidan() {
        if (!NetWorkUtil.isNetwork(getApplicationContext())) {
            Toast.makeText(getApplicationContext(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        infolist = new ArrayList<CaidanEntity>();
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        if (httptools == null) {
            httptools = new HttpTools(getApplicationContext());
        }
        //httptools.caidan(token, new JsonCaidan());

        if (mType == 0) {
            httptools.confirmFood(token, new JsonCaidan());
        } else {
            httptools.confirmGoods(token, new GoodsHandler());
        }
    }

    /**
     * 余额支付
     */
    private void Balancepay() {
        SharedPreferences sp = getSharedPreferences("spReg", Context.MODE_PRIVATE);
        token = sp.getString("data", "");

        //		Log.i("zq", "balancepayorderid---"+orderid);
        if (httptools == null) {
            httptools = new HttpTools(QuedingdingdanActivity.this);
        }
//		httptools.submitpay(token,orderid,new JsonHttpResponseHandler() {
//
//			@Override
//			public void onSuccess(int statusCode, Header[] headers,
//					JSONObject response) {
//				super.onSuccess(statusCode, headers, response);
//				try {
//					boolean code = response.getBoolean("code");
//					String msg = response.getString("msg");
//					Log.i("zq", "balancepay---"+response.toString());
//					if (code == true) {
//						//						String data=response.getString("data");
//						Toast.makeText(QuedingdingdanActivity.this, msg, Toast.LENGTH_SHORT).show();
//						Intent intent = new Intent();
//						intent.putExtra("code", "2");
//						intent.setClass(QuedingdingdanActivity.this, FanqiedingcanActivity.class);
//						startActivity(intent);
//						finish();
//					} else {
////						flag=false;
//						Intent intent = new Intent();
//						intent.putExtra("code", "2");
//						intent.setClass(QuedingdingdanActivity.this, FanqiedingcanActivity.class);
//						startActivity(intent);
//						Toast.makeText(QuedingdingdanActivity.this, msg, Toast.LENGTH_SHORT).show();
//						finish();
//					}
//				} catch (JSONException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//
//		});
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            /**
             * 点击空白位置 隐藏软键盘
             */
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    private class ConfirmOrderResponse extends JsonHttpResponseHandler {

        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(QuedingdingdanActivity.this, "请稍后....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
            Log.w("CONFIRM", response.toString());
            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code) {
                    if (mType == 1) {
                        int orderId = response.getInt("data");
                        submitGoodsOrder(orderId);
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra("code", "2");
                        intent.setClass(QuedingdingdanActivity.this, FanqiedingcanActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                              String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            MyShowDialog.closeLoadingDialog();
        }
    }

    private class GoodsHandler extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(QuedingdingdanActivity.this, "请稍后....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            Log.w("GOODS", response.toString());
            MyShowDialog.closeLoadingDialog();
            initRes();
            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code) {
                    JSONObject data = response.getJSONObject("data");
                    JSONArray carts = data.getJSONArray("shoppingcarts");
                    for (int i = 0; i < carts.length(); i++) {
                        JSONObject shoppingcarts = carts.getJSONObject(i);
                        String id = shoppingcarts.getString("id");
                        String productid = shoppingcarts.getString("productid");
                        String name1 = shoppingcarts.getString("name");
                        String amount = shoppingcarts.getString("amount");
                        String price = shoppingcarts.getString("price");
//						String sname = shoppingcarts.getString("sname");
                        heji += Double.parseDouble(price) * Double.parseDouble(amount);
                        shuliang += Integer.parseInt(amount);
                        Intent intent = new Intent();
                        intent.putExtra("shuliang", shuliang);
                        Log.i("zq", "heji" + heji);
                        infolist.add(new CaidanEntity(id, productid, amount, name1, price, ""));
                    }
                    tv_heji.setText(String.valueOf(heji));
                    caidanAdapter = new CaidanAdapter(getApplicationContext(), infolist);
                    lv.setAdapter(caidanAdapter);
                    lv.setDivider(null);
                } else {
                    finish();
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public class JsonCaidan extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(QuedingdingdanActivity.this, "请稍后....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            Log.w("CAIDAN", response.toString());
            try {
                MyShowDialog.closeLoadingDialog();
                initRes();
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code) {
                    JSONObject object = response.getJSONObject("data");
                    systime = object.getString("systime");
                    JSONArray array = object.getJSONArray("shoppingcarts");
                    for (int j = 0; j < array.length(); j++) {
                        JSONObject shoppingcarts = array.getJSONObject(j);
                        String id = shoppingcarts.getString("id");
                        String productid = shoppingcarts.getString("productid");
                        String name1 = shoppingcarts.getString("name");
                        String amount = shoppingcarts.getString("amount");
                        String price = shoppingcarts.getString("price");
//						String sname = shoppingcarts.getString("sname");
                        heji += Double.parseDouble(price) * Double.parseDouble(amount);
                        shuliang += Integer.parseInt(amount);
                        Intent intent = new Intent();
                        intent.putExtra("shuliang", shuliang);
                        Log.i("zq", "heji" + heji);
                        infolist.add(new CaidanEntity(id, productid, amount, name1, price, ""));
                    }
//					int total = (int)(heji*10);
                    tv_heji.setText("" + heji);
                    date = systime.substring(0, 10);
                    riqi = systime.substring(8, 10);
                    tv_time.setText("18:00");
                    caidanAdapter = new CaidanAdapter(getApplicationContext(), infolist);
                    lv.setAdapter(caidanAdapter);
                    lv.setDivider(null);
//					Utility.setListViewHeightBasedOnChildren(lv);
                } else {
                    finish();
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private class SubmitGoodsHandler extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            Log.w("SUBMIT", response.toString());
            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code) {
                    Intent intent = new Intent();
                    intent.putExtra("code", "2");
                    intent.setClass(QuedingdingdanActivity.this, FanqiedingcanActivity.class);
                    startActivity(intent);
                    finish();
                }
                Toast.makeText(QuedingdingdanActivity.this, msg, Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            Log.w("TTT", responseString);
        }
    }
}
